<?php
/**
 * Bdat Site development
 * @author Will Skates
 */

/*----------------------------------------------------------------------------------------------------*/

/**
 * Outline of properties and functionality required to manage user information information within the system.
 * @author Will Skates
 */
class useradmin extends CI_Model {
	
	public $current;
	
	public $minRole;
	public $maxRole;
	
	public $contentHtml = '';
	
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Launch this custom content admin system.
	 * @param 	Array	$args 	- A list of arguments passed to this class via the url.
	 * @return	Void
	 */
	public function launch($args)
	{
		
		//Get all of the user roles that are available.
		$sql = 'SELECT uid FROM user_roles';
		$res = $this->db->query($sql)->result();
		
		//Set the min and max roles dynamically.
		$this->minRole = reset($res)->uid;
		$this->maxRole = end($res)->uid;
		
		
		//If there is a function to run then run it with the rest of the arguments from the url.
		if ( 
			isset($args[0]) && !is_numeric($args[0]) &&
			isset($args[1]) && !isset($_POST['UserCSV'])
		) {
			$this->performAction($args[0],(int)$args[1]);
		} else if ( isset($_POST['UserCSV']) ) {
			//If we have user emails.
			$this->addUsers();
		}
		
		$this->addForm();
		$this->listUsers();
		
		$this->load->View('admin/pageView',array('content'=>$this->contentHtml));

	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Add new users using csv information passed to it by the add user form.
	 * @return	Void
	 */
	public function addUsers()
	{
		
		$this->load->model('users/user');
		$this->load->helper('email');
		
		//get a list of all the emails registered (we are going to use this to avoid duplicating user accounts).
		$adds = array();
		$query = 'select email from user_profiles';
		$result = $this->db->query($query)->result();
		
		foreach ( $result as $k=>$v ) {
			
			$adds[] = $v->email;
		
		}
		
		//Get the values comma separated.
		$data = str_replace(array(';',',',"\n","\r\n"),'%%MARKER%%',$_POST['UserCSV']);
		$data = explode('%%MARKER%%',$data);

		
		$u = new User();
		
		foreach ($data as $k=>$v) { 
			$v = trim($v); 
			
			//If the email is valid and no user has that email address then....
			if ( valid_email($v) && !in_array($v,$adds) ) {
				$u->createUser($v);
			}
		}
		
		
	}
	
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Create a html form to enable us to create users from a comma separated list. 
	 * Then place that in the html for the page.
	 * @return	Void
	 */
	public function addForm()
	{
		
		$this->load->helper('url');
		$this->load->library('zend','Zend/Form');
		$this->zend->load('Zend/Form');
		$this->zend->load('Zend/View');
		$this->zend->load('Zend/Form/Element/Textarea');
		$this->zend->load('Zend/Form/Element/Button');
		$this->zend->load('Zend/Form/Element/Submit');
		
		$form = new Zend_Form;
		//$form->setAction(current_url())->setMethod('post')->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
		$form->setAction(current_url())->setMethod('post');
		$form->setAttrib('id', 'AddUsers');
		
		$tA = new Zend_Form_Element_TextArea('UserCSV');
		$tA->setAttribs(array('cols'=>38));
		$sub = new Zend_Form_Element_Submit('UserFrmSubmit');
		$sub->setLabel('Submit' . ':');
		$sub->setAttribs(array('class' => 'roundBtn redBtn'));
		
		$form->addElement($tA,'tA');
		$form->addElement($sub,'Submit');
		
		$view = new Zend_View();
		$this->contentHtml .= '<h3 class="addUsers">Add a user</h3>' . $form->render($view);
	}
	
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Create a html table to display information regarding users within the system and allow you to change
	 * the level of access given to a user.
	 * @return	Void
	 */
	public function listUsers()
	{
		$this->load->model('admin/contentList');
		$uL = new contentList();
		$uL->hasEdit = false;
		$sql = 'SELECT 
					id as uid,
					username,
					user_profiles.name as realName,
					user_roles.name as role,
					role as roleid,
					user_profiles.isguesttweeter as guestTweeter
				FROM 
					users
				LEFT JOIN
					user_roles ON users.role = user_roles.uid
				LEFT JOIN
					user_profiles ON userid = users.id
		';
		$result = $this->db->query($sql)->result();
		$uL->customType = true;
		
		$keys = array_keys((Array)$result[0]);
		unset($keys[4]);
	
		$uL->setFields(array_merge($keys,array('promote','demote','view')));
		
		
		foreach ( $result as $key=>$val ) {
			
			if ( $val->roleid < $this->maxRole ) {
				$result[$key]->promote = '<a href="' . admin::$adminURL . 'other/show/User/promote/' . $val->uid . '/">Promote.</a>';
			} else {
				$result[$key]->promote = '<span class=\'grey\'>This user is a \'' . $val->role . '\' and cannot be promoted.</span>';
			}
			
			if ( $val->roleid > $this->minRole ) {
				$result[$key]->demote  = '<a href="' . admin::$adminURL . 'other/show/User/demote/' . $val->uid . '/">Demote.</a>';
			} else {
				$result[$key]->demote = '<span class=\'grey\'>This user is a \'' . $val->role . '\' and cannot be demoted.</span>';
			}
			
			if ( $val->guestTweeter == 0 ) {
				$result[$key]->guestTweeter  = '<a href="' . admin::$adminURL . 'other/show/User/gt/' . $val->uid . '/">Make this user the guest tweeter.</a>';
			} else {
				$result[$key]->guestTweeter = '<span class=\'yellow\'>This user is the current guest tweeter.</span>';
			}
			
			$result[$key]->view =  '<a href="' . admin::$adminURL . 'other/show/User/viewProf/' . $val->uid . '/">View Profile.</a>';
			
			unset($result[$key]->roleid);
			
		}
		
		$uL->init('User',$keys,$result);
		$this->contentHtml .= $uL->draw(false);
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Perform a function that is in the arguments for the url.
	 * @param	String	$action		- The name of the function (-Action,e.g. "demote" becomes "demoteAction").
	 * @param	Integer $id			- The unique identifier for the user on which the action is performed.
	 * @return 	Void
	 */
	public function performAction( $action, $id )
	{
		
		if ( method_exists($this,$action . 'Action') ) {
			$this->load->model('users/user');
			$this->current = new User();
			$this->current = $this->current->make($id);
			
			if ( $this->current !== false ) {
				$func = $action . 'Action';
				$this->$func();
			} else {
				
			}
			
		}
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Promote the given user if possible.
	 * @return	Void
	 */
	public function promoteAction()
	{
		
		if ( $this->current->role < $this->maxRole ) {
			$this->current->role++;
			$this->current->update(array('role'=>$this->current->role));
		}
		
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Demote the given user if possible.
	 * @return	Void
	 */
	public function demoteAction()
	{
		
		if ( $this->current->role > $this->minRole ) {
			$this->current->role--;
			$this->current->update(array('role'=>$this->current->role));
		}
		
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Delete the given user.
	 * @return	Void
	 */
	public function deleteAction()
	{
		$this->current->delete();
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * Make the given user the guest tweeter (make sure that there are no others as well).
	 * @return	Void
	 */
	public function gtAction()
	{
		
		$sql = 'UPDATE user_profiles SET isguesttweeter = 0;';
		$this->db->query($sql);
		$this->current->update(array('role'=>$this->current->role,'isguesttweeter'=>1));
		
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
	/**
	 * View the profile html for a given user and add it at the top of the html content for the page.
	 * @return	Void
	 */
	public function viewProfAction()
	{
		$this->contentHtml = $this->current->profile->draw() . $this->contentHtml;
	}
	
	/*----------------------------------------------------------------------------------------------------*/
	
}